import React, { Component } from 'react';
import { Form, Select, Input } from 'antd';
import PropTypes from 'prop-types';
const { Option } = Select;




/**
 * 品类保存表单
 */
class SaveForm extends Component {

    formRef = React.createRef();

    static propTypes = {
        type: PropTypes.string.isRequired,
        category: PropTypes.object,
        setForm: PropTypes.func.isRequired,
        // 添加功能需要的参数
        categorys: PropTypes.array,
        parentId: PropTypes.string
    }

    UNSAFE_componentWillMount(){
       // 将form对象通过setForm()传递父组件
       this.props.setForm(this.formRef);
    }
    
    // initialValues不动态更新解决方式
    componentDidUpdate() {
        this.formRef.current.setFieldsValue({
            name: this.props.category.name,
            parentId: this.props.parentId
        });
    }
    
    render() { 

        const { type, category, categorys } = this.props;

        return (
            <Form 
            ref={this.formRef}
            initialValues={{
                name: category.name,
                parentId: '0'
            }}
            >
                {type === 'add' && 
                <Form.Item 
                name="parentId" 
                label="一级分类"
                rules={[
                    { required: true, message: "一级分类不能为空" },
                ]}
                >
                    <Select
                        placeholder="选择分类"
                        allowClear
                    >   
                        <Option value="0">一级分类</Option>)
                        { categorys.map(v => <Option value={v['_id']}>{v.name}</Option>)}
                    </Select>
                </Form.Item>
                }
                <Form.Item 
                name="name" 
                label="分类名称"
                rules={[
                    { required: true, message: "分类名称不能为空" },
                ]}
                >
                    <Input placeholder='输入分类名称' />
                </Form.Item>
            </Form>
        );
    }
}
 
export default SaveForm;